﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using He.Common;
using System.Collections.Generic;
using System.Text;
using He.Web.UI;
namespace He.Web.manage.product
{
    public partial class edit : Manage
    {
        public string action = Enums.ActionEnum.Add.ToString(); //操作类型
        public int id;
        public int channel_id;
        public Model.channel channel;

        //页面初始化事件
        protected void Page_Init(object sernder, EventArgs e)
        {
            if (!int.TryParse(Request.Params["channel_id"] as string, out this.channel_id))
            {
                ShowParamError();
                return;
            }
            CreateAttrControl(this.channel_id); //动态生成相应的扩展字段控件
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string _action = GetString("action");
            if (!string.IsNullOrEmpty(_action) && _action == Enums.ActionEnum.Edit.ToString())
            {
                this.action = Enums.ActionEnum.Edit.ToString();//修改类型
                if (!int.TryParse(Request.QueryString["id"] as string, out this.id))
                {
                    ShowParamError();
                    return;
                }
            }

            channel = new BLL.channel().GetModel(channel_id);

            if (!Page.IsPostBack)
            {

                CategoryTreeBind(0, "请选择所属类别……", this.channel_id, ddlcategory_id);//分类绑定

                if (action == Enums.ActionEnum.Edit.ToString())
                {
                    chkLoginLevel("editChannel" + channel.id);
                    ShowInfo(this.id);
                }
                else
                {
                    chkLoginLevel("addChannel" + channel.id);
                }
            }
        }

        #region 返回相册列表HMTL=========================
        private string GetImgGroup(int _pid, string _img_urls)
        {
            if (!string.IsNullOrEmpty(_img_urls))
            {
                string[] _file_arr = _img_urls.Split(',');
                StringBuilder strTxt = new StringBuilder();
                foreach (string temp in _file_arr)
                {
                    strTxt.AppendLine("<li>");
                    strTxt.AppendLine(string.Format("<img src=\"{0}\" onclick=\"focus_img(this);\" />", temp));
                    strTxt.AppendLine("<br />");
                    strTxt.AppendLine(string.Format("<a href=\"{0}\" target=\"_blank\">原图</a>", temp));
                    strTxt.AppendLine(string.Format("<a href=\"javascript:void(0)\" onclick=\"dlstItems_Command(this,'{0}','{1}');\">删除</a>", _pid, temp));
                    strTxt.AppendLine(string.Format("<input name=\"hideFiles\" type=\"hidden\" value=\"{0}\">", temp));
                    strTxt.AppendLine("</li>");
                }
                return strTxt.ToString();
            }
            return string.Empty;
        }
        #endregion

        #region 创建扩展字段控件=========================
        private void CreateAttrControl(int cid)
        {
            List<Model.attr_field> fieldList = new BLL.attr_field().GetModelList("is_lock=0 and channel_id=" + cid);

            //赋值扩展字段
            if (fieldList != null)
            {
                field_tab_content.Visible = true;
                foreach (Model.attr_field item in fieldList)
                {
                    //创建一个dl标签
                    HtmlTableRow htmlTR = new HtmlTableRow();
                    HtmlTableCell htmlTD = new HtmlTableCell();
                    HtmlTableCell htmlTD2 = new HtmlTableCell();

                    htmlTD.Attributes["width"] = "15%";
                    htmlTD.Attributes["align"] = "right";

                    htmlTD.InnerHtml = item.title;

                    switch (item.control_type)
                    {
                        case "single-text": //单行文本
                            //创建一个TextBox控件
                            TextBox txtControl = new TextBox();
                            txtControl.ID = "field_control_" + item.name;
                            //CSS样式及TextMode设置
                            if (item.control_type == "single-text")
                            {
                                txtControl.CssClass = "input w380";
                            }
                            else if (item.control_type == "multi-text")
                            {
                                txtControl.CssClass = "textarea wh380";
                                txtControl.TextMode = TextBoxMode.MultiLine;
                            }
                            else if (item.control_type == "number")
                            {
                                txtControl.CssClass = "input small number";
                            }
                            if (item.is_required == 1)
                            {
                                txtControl.CssClass = txtControl.CssClass + " required";
                            }
                            //设置默认值
                            txtControl.Text = item.default_value;
                            //验证提示信息
                            txtControl.Attributes.Add("HintTitle", item.title);
                            txtControl.Attributes.Add("HintInfo", item.tip_msg);
                            //将控件添加至DD中
                            htmlTD2.Controls.Add(txtControl);
                            break;
                        case "multi-text": //多行文本
                            goto case "single-text";
                        case "number": //数字
                            goto case "single-text";
                        case "editor"://编辑器
                            HtmlTextArea txtTextArea = new HtmlTextArea();
                            txtTextArea.ID = "field_control_" + item.name;
                            txtTextArea.Attributes.Add("style", "visibility:hidden;");
                            //是否简洁型编辑器
                            if (item.editor_type == 1)
                            {
                                txtTextArea.Attributes.Add("class", "editor-mini");
                            }
                            else
                            {
                                txtTextArea.Attributes.Add("class", "editor");
                            }
                            txtTextArea.Value = item.default_value; //默认值
                            //将控件添加至TD中
                            htmlTD2.Controls.Add(txtTextArea);
                            break;
                        case "checkbox": //复选框
                            CheckBox cbControl = new CheckBox();
                            cbControl.ID = "field_control_" + item.name;
                            //默认值
                            if (item.default_value == "1")
                            {
                                cbControl.Checked = true;
                            }

                            //将控件添加至DD中
                            htmlTD2.Controls.Add(cbControl);
                            break;
                        case "multi-radio": //多项单选
                            RadioButtonList rblControl = new RadioButtonList();
                            rblControl.ID = "field_control_" + item.name;
                            rblControl.RepeatDirection = RepeatDirection.Horizontal;
                            rblControl.RepeatLayout = RepeatLayout.Flow;
                            //赋值选项
                            List<Model.attr_item> itemList = new BLL.attr_item().GetModelList("field_id=" + item.id);
                            foreach (Model.attr_item attrItem in itemList)
                            {
                                rblControl.Items.Add(new ListItem(attrItem.title, attrItem.title));
                            }
                            //默认值
                            rblControl.SelectedValue = item.default_value;
                            //将控件添加至TD中
                            htmlTD2.Controls.Add(rblControl);
                            break;
                        case "multi-checkbox": //多项多选
                            CheckBoxList cblControl = new CheckBoxList();
                            cblControl.ID = "field_control_" + item.name;
                            cblControl.RepeatDirection = RepeatDirection.Horizontal;
                            cblControl.RepeatLayout = RepeatLayout.Flow;
                            //赋值选项
                            List<Model.attr_item> itemList2 = new BLL.attr_item().GetModelList("field_id=" + item.id);
                            foreach (Model.attr_item attrItem in itemList2)
                            {
                                cblControl.Items.Add(new ListItem(attrItem.title, attrItem.id.ToString()));
                            }
                            cblControl.SelectedValue = item.default_value; //默认值
                            //将控件添加至TD中
                            htmlTD2.Controls.Add(cblControl);
                            break;
                        case "images":
                            FileUpload fileControl = new FileUpload();
                            fileControl.ID = "field_control_" + item.name;
                            htmlTD2.Controls.Add(fileControl);
                            break;
                    }
                    //将TD添加到TR中
                    htmlTR.Controls.Add(htmlTD);
                    htmlTR.Controls.Add(htmlTD2);
                    //将TR添加至field_tab_content中
                    field_tab_content.Controls.Add(htmlTR);
                }
            }
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            Model.article model = new BLL.article().GetModel(_id);
            txtTitle.Text = model.title;
            txtPrice.Text = model.price.ToString();
            ddlcategory_id.SelectedValue = model.category_id.ToString();
            txtSeoKeywords.Text = model.seo_keywords;
            txtSeoDescription.Text = model.seo_desc;
            txtContent.Value = model.content;
            txtLinkUrl.Text = model.link_url;
            chkRed.Checked = model.is_red == 1 ? true : false;
            chkHot.Checked = model.is_hot == 1 ? true : false;
            chkLock.Checked = model.is_lock == 1 ? true : false;
            txtClick.Text = model.click.ToString();
            txtSortId.Text = model.sort_id.ToString();
            txtAddTime.Text = model.add_time ?? DateTime.Now.ToString("yyyy-MM-dd");
            //赋值上传的相册
            LitImgGroup.Text = GetImgGroup(model.id, model.img_urls);
            //扩展字段赋值
            List<Model.attr_field> ls1 = new BLL.attr_field().GetModelList("is_lock=0 and channel_id=" + channel_id);
            foreach (Model.attr_field attrfieldItem in ls1)
            {
                Model.attr_value attrvalue = new BLL.attr_value().GetModel(string.Format("picture_id={0} and field_id={1}", model.id, attrfieldItem.id));
                switch (attrfieldItem.control_type)
                {
                    case "single-text": //单行文本
                        TextBox txtControl = FindControl("field_control_" + attrfieldItem.name) as TextBox;
                        if (txtControl != null && attrvalue != null)
                        {
                            txtControl.Text = attrvalue.content;
                        }
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        HtmlTextArea txtAreaControl = FindControl("field_control_" + attrfieldItem.name) as HtmlTextArea;
                        if (txtAreaControl != null && attrvalue != null)
                        {
                            txtAreaControl.Value = attrvalue.content;
                        }
                        break;
                    case "images": //图片上传

                        break;
                    case "number": //数字
                        goto case "single-text";
                    case "checkbox": //复选框
                        CheckBox cbControl = FindControl("field_control_" + attrfieldItem.name) as CheckBox;
                        if (cbControl != null && attrvalue != null)
                        {
                            if (attrvalue.content == "1")
                            {
                                cbControl.Checked = true;
                            }
                            else
                            {
                                cbControl.Checked = false;
                            }
                        }
                        break;
                    case "multi-radio": //多项单选
                        RadioButtonList rblControl = FindControl("field_control_" + attrfieldItem.name) as RadioButtonList;
                        if (rblControl != null && attrvalue != null)
                        {
                            rblControl.SelectedValue = attrvalue.content;
                        }
                        break;
                    case "multi-checkbox": //多项多选
                        CheckBoxList cblControl = FindControl("field_control_" + attrfieldItem.name) as CheckBoxList;
                        if (cblControl != null && attrvalue != null)
                        {
                            string[] valArr = attrvalue.content.Trim(',').Split(',');
                            for (int i = 0; i < cblControl.Items.Count; i++)
                            {
                                cblControl.Items[i].Selected = false; //先取消默认的选中
                                foreach (string str in valArr)
                                {
                                    if (cblControl.Items[i].Value == str)
                                    {
                                        cblControl.Items[i].Selected = true;
                                    }
                                }
                            }
                        }
                        break;
                }
            }
        }
        #endregion

        #region 扩展字段赋值=============================
        private List<Model.attr_value> SetAttrValues(int _channel_id, int pid)
        {
            DataTable dt = new BLL.attr_field().GetList("is_lock=0 and channel_id=" + channel_id).Tables[0];
            List<Model.attr_value> ValueList = new List<Model.attr_value>();
            foreach (DataRow dr in dt.Rows)
            {
                //查找相应的控件
                switch (dr["control_type"].ToString())
                {
                    case "single-text": //单行文本
                        TextBox txtControl = FindControl("field_control_" + dr["name"].ToString()) as TextBox;
                        if (txtControl != null)
                        {
                            ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), txtControl.Text.Trim()));
                        }
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        HtmlTextArea htmlTextAreaControl = FindControl("field_control_" + dr["name"].ToString()) as HtmlTextArea;
                        if (htmlTextAreaControl != null)
                        {
                            ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), htmlTextAreaControl.Value));
                        }
                        break;
                    case "images": //图片上传
                        goto case "single-text";
                    case "number": //数字
                        goto case "single-text";
                    case "checkbox": //复选框
                        CheckBox cbControl = FindControl("field_control_" + dr["name"].ToString()) as CheckBox;
                        if (cbControl != null)
                        {
                            if (cbControl.Checked == true)
                            {
                                ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), "1"));
                            }
                            else
                            {
                                ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), "0"));
                            }
                        }
                        break;
                    case "multi-radio": //多项单选
                        RadioButtonList rblControl = FindControl("field_control_" + dr["name"].ToString()) as RadioButtonList;
                        if (rblControl != null)
                        {
                            ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), rblControl.SelectedValue));
                        }
                        break;
                    case "multi-checkbox": //多项多选
                        CheckBoxList cblControl = FindControl("field_control_" + dr["name"].ToString()) as CheckBoxList;
                        if (cblControl != null)
                        {
                            StringBuilder tempStr = new StringBuilder();
                            for (int i = 0; i < cblControl.Items.Count; i++)
                            {
                                if (cblControl.Items[i].Selected)
                                {
                                    tempStr.Append(cblControl.Items[i].Value.Replace(',', '，') + ",");
                                }
                            }
                            string ids = "," + tempStr.ToString().Trim(',') + ",";
                            ValueList.Add(AddAttrValue(pid, Convert.ToInt32(dr["id"]), dr["name"].ToString(), ids));
                        }
                        break;
                }
            }
            return ValueList;
        }

        private Model.attr_value AddAttrValue(int pid, int fieldId, string fieldName, string content)
        {
            Model.attr_value attrvalue = new Model.attr_value()
            {
                picture_id = pid,
                field_id = fieldId,
                field_name = fieldName,
                content = content
            };
            return attrvalue;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            Model.article model = new Model.article();
            BLL.article bll = new BLL.article();

            model.title = txtTitle.Text.Trim();
            //取得图片集合,添加相片
            string firstImg = "";
            string hideFiles = Request.Params["hideFiles"];
            if (!string.IsNullOrEmpty(hideFiles))
            {
                string[] fileArr = hideFiles.Split(',');
                firstImg = fileArr[0];
            }
            else
            {
                hideFiles = string.Empty;
            }

            if (channel.is_thumb == 1 && !string.IsNullOrEmpty(firstImg))
            {
                model.img_url = "/uploadfiles/thumb/" + DateTime.Now.ToFileTime().ToString() + ".jpg";
                ImageHelper.CompressImage(firstImg, model.img_url, channel.img_width, channel.img_height, "max");
            }
            else
            {
                model.img_url = firstImg;
            }

            model.img_urls = hideFiles;

            model.price = decimal.Parse(txtPrice.Text.Trim());
            model.category_id = int.Parse(ddlcategory_id.SelectedValue);
            model.content = txtContent.Value;
            model.link_url = txtLinkUrl.Text.Trim();
            model.click = int.Parse(txtClick.Text.Trim());
            model.sort_id = int.Parse(txtSortId.Text.Trim());
            model.seo_keywords = txtSeoKeywords.Text.Trim();
            //自动提取SEO描述
            if (txtSeoDescription.Text.Trim() != string.Empty)
            {
                model.seo_desc = txtSeoDescription.Text;
            }
            else
            {
                model.seo_desc = He.Common.StringHelper.ClearHtmlTags(txtContent.Value, 250);
            }
            model.is_top = 0;
            model.is_red = chkRed.Checked ? 1 : 0;
            model.is_hot = chkHot.Checked ? 1 : 0;
            model.is_lock = chkLock.Checked ? 1 : 0;
            model.add_time = txtAddTime.Text.Trim();
            int aid = bll.Add(model);
            if (aid > 0)
            {
                //增加扩展字段
                BLL.attr_value attrbll = new BLL.attr_value();
                List<Model.attr_value> AttrValues = SetAttrValues(channel_id, aid);
                attrbll.AddModelList(AttrValues);
                SaveLogs(string.Format("[{0}管理]增加内容:{1}", channel.manage_title, model.title));
                return true;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            BLL.article bll = new BLL.article();
            Model.article model = bll.GetModel(_id);
            model.title = txtTitle.Text.Trim();
            model.price = Convert.ToDecimal(txtPrice.Text.Trim());
            model.category_id = int.Parse(ddlcategory_id.SelectedValue);
            //检查图片是否有变
            string hideFiles = Request.Params["hideFiles"];
            if (!string.IsNullOrEmpty(hideFiles))
            {
                string[] fileArr = hideFiles.Split(',');

                if (channel.is_thumb == 1)
                {
                    //删除旧的缩略图
                    FileHelper.DeleteFile(model.img_url);
                    //生成新的缩略图
                    model.img_url = "/uploadfiles/thumb/" + DateTime.Now.ToFileTime().ToString() + ".jpg";
                    ImageHelper.CompressImage(fileArr[0], model.img_url, channel.img_width, channel.img_height, "max");
                }
                else
                {
                    if (model.img_url.Substring(model.img_url.LastIndexOf("/") + 1) != fileArr[0].Substring(fileArr[0].LastIndexOf("/") + 1))
                    {
                        //删除旧的缩略图
                        FileHelper.DeleteFile(model.img_url);
                        //生成缩略图
                        model.img_url = fileArr[0];
                    }
                }
            }
            else
            {
                //删除旧的缩略图
                FileHelper.DeleteFile(model.img_url);
                //没有图片
                model.img_url = "";
            }
            model.seo_keywords = txtSeoKeywords.Text.Trim();
            //自动提取SEO描述
            if (txtSeoDescription.Text.Trim() != string.Empty)
            {
                model.seo_desc = txtSeoDescription.Text;
            }
            else
            {
                model.seo_desc = He.Common.StringHelper.ClearHtmlTags(txtContent.Value, 250);
            }

            model.content = txtContent.Value;
            model.link_url = txtLinkUrl.Text.Trim();
            model.is_red = chkRed.Checked == true ? 1 : 0;
            model.is_hot = chkHot.Checked == true ? 1 : 0;
            model.is_lock = chkLock.Checked == true ? 1 : 0;
            model.click = int.Parse(txtClick.Text.Trim());
            model.sort_id = int.Parse(txtSortId.Text.Trim());
            model.add_time = txtAddTime.Text.Trim();
            if (bll.Update(model))
            {
                //修改扩展字段
                BLL.attr_value attrbll = new BLL.attr_value();
                List<Model.attr_value> AttrValues = SetAttrValues(channel_id, model.id);
                attrbll.UpdateModelList(AttrValues);
                SaveLogs(string.Format("[{0}管理]修改内容:{1}", channel.manage_title, model.title));
                return true;
            }
            return false;
        }
        #endregion

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (action == Enums.ActionEnum.Edit.ToString()) //修改
            {
                if (!DoEdit(this.id))
                {
                    ShowError("保存过程中发生错误啦！");
                    return;
                }
                ShowSuccess("修改信息成功啦！", LastListUrl);
            }
            else //添加
            {
                if (!DoAdd())
                {
                    ShowError("保存过程中发生错误啦！");
                    return;
                }
                ShowSuccess("添加信息成功啦！", Request.RawUrl);
            }
        }
    }
}
